package com.cy.pj.notice.dao.impl;

import com.cy.pj.notice.dao.MyDao;
import com.cy.pj.notice.util.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Component
@Repository
public class MyDaoImpl implements MyDao {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private MyUtil myUtil;

    @Override
    public List<Map<String, Object>> selectAll() throws SQLException {
        List<Map<String, Object>> list = new ArrayList<>();

        Connection connection = dataSource.getConnection();

        String sql = "select * from sys_notices";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        ResultSet resultSet = null;
        boolean execute = preparedStatement.execute();
        if (execute){
            resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            while (resultSet.next()) {
                Map<String, Object> map = new HashMap<>();
                for (int i = 0; i < columnCount; i++) {
                    String columnLabel = metaData.getColumnLabel(i+1);
                    map.put(columnLabel, resultSet.getObject(columnLabel));
                }
                list.add(map);
            }
        }
        connection.close();
        preparedStatement.close();
        resultSet.close();
        return list;
    }

    @Override
    public List<Map<String, Object>> testMyUtil(String sql) throws SQLException {
        List<Map<String, Object>> result = myUtil.getResult(sql);
        return result;
    }
}
